<?php
namespace org\kahikai\database\mysql;

require_once dirname(__FILE__) . '/../PaperDao.php';
require_once dirname(__FILE__) . '/KahikaiMysql.php';
require_once dirname(__FILE__) . '/../../domain/Paper.php';

use org\kahikai\database\PaperDao;
use org\kahikai\domain\Paper;

/**
 * 
 * @author ch4mp
 *
 */
class MysqlPaperDao implements PaperDao {
	
	/**
	 *
	 * @return an array with all Papers per Species id
	 */
	public function getAll() {
		$papers = array();
		
		$result = KahikaiMysql::query('SELECT id, url, species_id FROM PAPER');
		while ($record = $result->fetch_assoc()) {
			if(!array_key_exists($record['species_id'], $papers)) {
				$papers[$record['species_id']] = array();
			}
			$papers[$record['species_id']][$record['id']] = new Paper($record['id'], $record['url']);
		}
		$result->close();
		
		return $papers;
	}
	
	/**
	 *
	 * @param int $id a Language id
	 * @return the Paper with provided id or null
	 */
	public function getById($id) {
		$paper = null;
		
		$result = KahikaiMysql::query('SELECT url FROM PAPER');
		if ($record = $result->fetch_assoc()) {
			$paper = new Paper($id, $record['url']);
		}
		$result->close();
		
		return $paper;
	}
	
	/**
	 *
	 * @param int $speciesId a Species id
	 * @return an array with all Papers for provided Species (never null even if species id is unknown)
	 */
	public function getBySpeciesId($speciesId) {
		$papers = array();
		
		$result = KahikaiMysql::query("SELECT id, url FROM PAPER WHERE species_id=$speciesId");
		while ($record = $result->fetch_assoc()) {
			$papers[$record['id']] = new Paper($record['id'], $record['url']);
		}
		$result->close();
		
		return $papers;
	}
}
?>